package com.chaosj.memory;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.text.StrFormatter;
import lombok.SneakyThrows;
import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

/**
 * @className: ScrapeReadMe
 * @description:
 * @author: caoyangjie
 * @date: 2022/3/10
 **/
public class ScrapeWriterBlog {

    public static void main(String[] args) {
        startScrape();
    }

    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入: " + tip + "");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new RuntimeException("输入路径不正确!");
    }

    @SneakyThrows
    public static void startScrape(){
        CmdParserHandler handler = new CmdParserHandler();
        String mdPath = scanner("待完善的markdown文档路径:");
        List<String> scrapeUris = new ArrayList<>();
        scrapeUris.add("writer");
        scrapeUris.add(mdPath);
        Files.readAllLines(Paths.get(mdPath)).parallelStream().forEach(line->{
            extractURI(line, scrapeUris);
        });
        handler.execute( scrapeUris.toArray(new String[scrapeUris.size()]) , new StringBuffer());
    }

    private static boolean filter(String uri) {
        return uri.startsWith("https://") || uri.startsWith("http://");
    }

    private static void extractURI(String line, List<String> scrapeUris){
        String remainingLine = line;
        while ( remainingLine.indexOf("](")!=-1 && remainingLine.indexOf(")")!=-1 ) {
            String uri = remainingLine.substring(remainingLine.indexOf("](")+2, remainingLine.indexOf(")"));
            remainingLine = line.substring(line.indexOf(")"));
            if( filter(uri) ){
                scrapeUris.add(uri);
                System.out.println(StrFormatter.format("request uri => {}", uri));
            }
        }
    }
}
